######################################################################
#
# The GAE SWF Project (http://gaeswf.appspot.com)
#
# Photo upload/download handlers. These manage photo requests.
# (Note that the authToken scheme exists because Flash's FileReference
# feature for uploads/downloads has a bug where it doesn't send along
# session information. We need the authToken to authenticate users
# for uploads.)
# 
# Copyright (c) 2008 Aral Balkan. Released under the MIT license.
#
# Learn more about Google App Engine and other cool stuff at
# the Singularity Web Conference: Online on October 24-26, 2008
# http://singularity08.com
#
# Blog: http://aralbalkan.com
#
######################################################################

import wsgiref.handlers
from google.appengine.ext import webapp

from models.models import Dataset

from google.appengine.ext import db

import logging

import string

class DocumentUploadHandler(webapp.RequestHandler):
	
	def post(self):
		uploadedDoc = self.request.get('upload')
		token = self.request.get('token')
		
		logging.info("Document upload with token:"+token)
		dataset = Dataset()
		dataset.token = token
		dataset.ip = self.request.remote_addr
		dataset.fileBlob = db.Blob(str(uploadedDoc))
		dataset.put()
		
		self.response.out.write(True)
		
	def get(self):
	   logging.info("Uploaded called without an actual POST!")
						
class DocumentDownloadHandler(webapp.RequestHandler):

	def get(self):
		
		token = self.request.get('token')
		dataset = Dataset.all().filter("token = ", token).get()
		
		if dataset:
			logging.info("Returning dataset!")
			# TODO: We really need to return the right content-type. Right now I'm returning JPEG for everything.
			self.response.headers['Content-Type'] = "text/xml"	
			self.response.headers['content-disposition'] = 'attachment; filename="UserDataset.bade"'
			self.response.out.write(dataset.fileBlob)
			
			dataset.delete()

		else:
			# Unauthorized
			self.error(401)